package com.mego.weblink.activitys;


import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.mego.weblink.BuildConfig;
import com.mego.weblink.R;
import com.mego.weblink.database.dbmodel.SystemAllInfo;
import com.mego.weblink.database.manager.SystemCenter;
import com.mego.weblink.version.UpdateManager;

import java.io.File;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.ItemDialog;
import zuo.biao.library.util.MD5Util;

public class WebActivity extends BaseActivity implements View.OnClickListener, ItemDialog.OnDialogItemClickListener, AlertDialog.OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener, UpdateManager.InstallCallBack {


    public static final String INTENT_RANGE = "INTENT_RANGE";
    public static final String RESULT_CLICKED_ITEM = "RESULT_CLICKED_ITEM";
    public static final String MEGO_TP = "http://aps.acciot.com.tw/index/tzapp/";
    public static final int INITFINISH = 1101;

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    private final String TAG = "WebActivity";
    private final int REQUEST_TO_DOPAY = 25;
    private final int FILE_CHOOSER_RESULT_CODE = 30;
    private final int REQUEST_TO_TZ = 40;
    ValueCallback<Uri> uploadMessage;
    ValueCallback<Uri[]> uploadMessageAboveL;
    ProgressDialog mPB;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == INITFINISH) {
                if (mPB != null) {
                    mPB.dismiss();
                    mPB = null;
                }
            }
        }
    };
    //<--- 安装apk---
    String apkpath = "";
    private ProgressBar pbWebView;
    private WebView wvWebView;
    private long firstTime = 0;//第一次返回按钮计时

    public static Intent createIntent(Context context) {
        return new Intent(context, WebActivity.class);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_activity);

        initView();
        initData();
        initEvent();

    }

    @Override
    public void initView() {
        pbWebView = findView(R.id.pbWebView);
        wvWebView = findView(R.id.wvWebView);
    }

    @SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
    @Override
    public void initData() {

        WebSettings webSettings = wvWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        wvWebView.requestFocus();

        // 设置setWebChromeClient对象
        wvWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    pbWebView.setVisibility(View.GONE);
                } else {
                    pbWebView.setVisibility(View.VISIBLE);
                    pbWebView.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            //For Android API < 11 (3.0 OS)
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android API >= 11 (3.0 OS)
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android API >= 21 (5.0 OS)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

        wvWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                wvWebView.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pbWebView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pbWebView.setVisibility(View.GONE);
            }
        });

        wvWebView.loadUrl(MEGO_TP);

    }

    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    @Override
    public void onBackPressed() {
        if (wvWebView.canGoBack()) {
            wvWebView.goBack();
            return;
        }

        super.onBackPressed();
    }

    @Override
    public void initEvent() {
        findViewById(R.id.tv_exit).setOnClickListener(this);
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);

        findViewById(R.id.tv_add).setOnClickListener(this);
    }

    @Override
    public void onForwardClick(View v) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_exit:
                moveTaskToBack(true); //Activity不销毁，直接进入后台
                break;
            case R.id.tv_add:
                onAdd();
                break;

        }
    }

    private void onAdd() {
        toActivity(TaizhuActivity.createIntent(context), REQUEST_TO_TZ, false);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                break;
            case KeyEvent.KEYCODE_BACK:
                if (wvWebView.canGoBack()) {
                    wvWebView.goBack();
                } else {
                    onExit();
                }
                return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    void onExit() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            showShortToast(getString(R.string.texit));
            firstTime = secondTime;
        } else {//完全退出
            moveTaskToBack(false);//应用退到后台
            System.exit(0);
        }

    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }
        if (requestCode == 100) {

        }
    }

    @Override
    public void onDialogItemClick(int requestCode, int position, String item) {

    }

    @RequiresApi(api = Build.VERSION_CODES.ECLAIR_MR1)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }

        switch (requestCode) {
            case REQUEST_TO_DOPAY:
                break;
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    @Override
    public void onTimerStart() {

    }

    @Override
    public void onTimerRefresh() {

    }

    @Override
    public void onTimerStop() {

    }

    @Override
    protected void onResume() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            wvWebView.onResume();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            wvWebView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
        if (wvWebView != null) {
            wvWebView.destroy();
            wvWebView = null;
        }
        super.onDestroy();
    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    private String getDeviceId() {

        SystemAllInfo info = SystemCenter.getInstance().getSysInfo("SERIAL");
        if (info == null) {
            //自动生成IMEI
            String code = Build.SERIAL;
            if (code.isEmpty() || code.compareToIgnoreCase("unknown") == 0) {
                code = MD5Util.MD5(System.currentTimeMillis() + Build.PRODUCT);
            }
            int max = 15;
            int size = code.length();
            if (size < max) {
                for (int i = size; i < max; i++) {
                    code += "0";
                }
            } else if (size > max) {
                code = code.substring(size - max);
            }
            info = new SystemAllInfo(null, "SERIAL", code.toLowerCase());
            SystemCenter.getInstance().saveSysInfo(info);
        }

        return info.getContent();
    }

    void installAPK(String filePath) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            /* Android N 写法*/
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(WebActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", new File(apkpath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            /* Android N之前的老版本写法*/
            intent.setDataAndType(Uri.fromFile(new File(apkpath)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            installAPK(apkpath);
        }
    }

    @Override
    public void doInstall(String filePath) {

        apkpath = filePath;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                installAPK(apkpath);
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        }
    }
    //---安装apk--->

}

